<template>

    
<div style="margin-top: 20px;margin-left: 20px;">
<div>
        <h4 style="color:dodgerblue;font-weight: 600;">养殖信息&ensp;&ensp;<el-button
                @click="dialogVisible = true">设置</el-button></h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="品种：">{{ form.breed }}</el-descriptions-item>
            <el-descriptions-item label="来源：">{{ form.source }}</el-descriptions-item>
            <el-descriptions-item label="饲养天数：">{{ form.feeding }}</el-descriptions-item>
            <el-descriptions-item label="饲养品牌：">{{ form.brand }}</el-descriptions-item>
            <el-descriptions-item label="饲养负责人：">{{ form.principal }}</el-descriptions-item>
            <el-descriptions-item label="出栏日期：">{{ form.publicationDate }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:dodgerblue;font-weight: 600;">保健信息&ensp;&ensp;<el-button @click="addTable()">新增行</el-button>
        </h4>
        <br />
        <hr /><br />
        <el-table :data="immuneList"
            :header-cell-style="{ backgroundColor: '#d6d6d6', color: '#000000', fontSize: '14px' }">
            <el-table-column label=" 饲养天数">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model="immuneInfo.feedingDays" />
                    </span>
                    <span v-else>
                        {{ scope.row.feedingDays }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="保健方式">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model="immuneInfo.healthCareMode" />
                    </span>
                    <span v-else>
                        {{ scope.row.healthCareMode }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="保健方法">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model="immuneInfo.healthCareMethod" />
                    </span>
                    <span v-else>
                        {{ scope.row.healthCareMethod }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-button @click="Addimmune()">保存</el-button>
                        <el-button @click="getimmnueList()">取消</el-button>
                    </span>
                    <span v-else>
                        <el-button @click="scope.row.isShow = true, getimmuseinfo(scope.row.id)">修改</el-button>
                        <el-button @click="deltimmnue(scope.row.id)">删除</el-button>
                    </span>
                </template>
            </el-table-column>
        </el-table>
        <br /> <br />
        <h4 style="color:dodgerblue;font-weight: 600;">动检证</h4>
        <br />
        <hr /><br />
        <el-upload v-model="fileList" action="http://localhost:5020/api/Uploads/Upload"
            list-type="picture-card" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4 style="color:dodgerblue;font-weight: 600;">企业信息&ensp;&ensp;<el-button
                @click="dialogVisible1 = true">设置</el-button>
        </h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="养殖场：">{{ form1.companyName }}</el-descriptions-item>
            <el-descriptions-item label="负责人：">{{ form1.principal }}</el-descriptions-item>
            <el-descriptions-item label="存栏数量：">{{ form1.quantity == undefined ? "" : form1.quantity + "只"
                }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:dodgerblue;font-weight: 600;">企业照片</h4>
        <br />
        <el-upload v-model="fileList1" action="http://localhost:5020/api/Uploads/Upload"
            list-type="picture-card" :on-remove="handleRemove1" :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload1">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
    </div>


    <!-- 添加养殖信息 -->
    <el-dialog v-model="dialogVisible" title="养殖信息" width="500">
        <template #footer>
            <div class="dialog-footer">
                <el-form ref="ruleFormRef" style="width: 400px;margin: 5px auto;" :model="form" :rules="rules"
                    label-width="auto" class="demo-ruleForm">
                    <el-form-item label="品种:" prop="breed">
                        <el-input v-model="form.breed" placeholder="请输入品种" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="来源:" prop="source">
                        <el-input v-model="form.source" placeholder="请输入来源" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="饲养天数:" prop="feeding">
                        <el-input v-model="form.feeding" placeholder="请输入饲养天数" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="饲料品牌:" prop="brand">
                        <el-input v-model="form.brand" placeholder="请输入饲料品牌" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="饲养负责人:" prop="Principal">
                        <el-input v-model="form.Principal" placeholder="请输入饲养负责人" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="出栏日期" prop="BreedingStock">
                        <el-date-picker v-model="form.BreedingStock" placeholder="请输入出栏日期" style="width: 100%" />
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>


            </div>
        </template>
    </el-dialog>

    <!-- 企业信息添加 -->
    <el-dialog v-model="dialogVisible1" title="企业信息" width="500">
        <template #footer>
            <div class="dialog-footer">
                <el-form ref="ruleFormRef" style="width: 400px;margin: 5px auto;" :model="form1" :rules="rules1"
                    label-width="auto" class="demo-ruleForm">
                    <el-form-item label="养殖场:" prop="Farm">
                        <el-input v-model="form1.Farm" placeholder="请输入养殖场" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="负责人:" prop="principal">
                        <el-input v-model="form1.principal" placeholder="请输入负责人" maxlength="30" show-word-limit />
                    </el-form-item>
                    <el-form-item label="存栏数量(只):" prop="quantity">
                        <el-input v-model="form1.quantity" placeholder="请输入存栏数量(只)" maxlength="30" show-word-limit />
                    </el-form-item>

                </el-form>
                <el-button type="primary" @click="submitForm1(ruleFormRef)">保存</el-button>


            </div>
        </template>
    </el-dialog>
</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import type { AxiosStatic } from 'axios'
import { ElMessage, ElMessageBox, type UploadProps, type UploadUserFile } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Cookies from 'cookies-ts'
import axios from 'axios'
import {useRoute} from 'vue-router'

const addadd=()=>{
    console.log("addadd")
}

const route = useRoute();
const cookie = new Cookies();



const fileList = ref<UploadUserFile[]>([])
const fileList1 = ref<UploadUserFile[]>([])


const dialogVisible = ref(false)
const dialogVisible1 = ref(false)




//养殖信息
const form = reactive({
    Farm: 0,
    Farm: "",
    Principal: "",
    BreedingStock: 0,
    BreedingId: 0,
     Bread: "",
    Source: "",
    FeedingDay: 0,
    BreedingBrand: "",
    HeadFeeder:"",
})
//公司信息
const form1 = reactive({
    id: 0,
    companyName: "",
    quantity: "",
    campanyImage: "",
    ptImeId: "",
    principal: "",
    businessCode: ""
})

const ruleFormRef = ref<FormInstance>()
//验证
const rules = reactive<FormRules>({
    breed: [
        { required: true, message: '品种不能为空', trigger: 'blur' },
    ],
    source: [
        { required: true, message: '来源不能为空', trigger: 'blur' },
    ],
    feeding: [
        { required: true, message: '饲养天数不能为空', trigger: 'blur' },
    ],
    brand: [
        { required: true, message: '饲料品牌不能为空', trigger: 'blur' },
    ],
    principal: [
        { required: true, message: '饲养负责人不能为空', trigger: 'blur' },
    ],
    publicationDate: [
        { required: true, message: '出栏日期不能为空', trigger: 'change' },
    ],
})
const rules1 = reactive<FormRules>({
    Farm: [
        { required: true, message: '养殖场不能为空', trigger: 'blur' },
    ],
    Principal: [
        { required: true, message: '负责人不能为空', trigger: 'blur' },
    ]
})

//添加养殖方法（修改）
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            dialogVisible.value = true;
            form.pTimeId = cookie.get("pTimeId") || "";
            if (form.id == undefined) {
                axios?.post("api/Cultivation/CultivationAdd", form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success("成功");
                        dialogVisible.value = false;
                    } else {
                        ElMessage.error("失败");
                    }
                })
            } else {
                axios?.put("api/Cultivation/CultivationUpdate", form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success("成功");
                        dialogVisible.value = false;
                    } else {
                        ElMessage.error("失败");
                    }
                })
            }

        }
    })
}
//反填养殖信息
const getCultAtionInfo = () => {
    axios?.get("http://localhost:5020/api/InsertTraceabilityManagements/GetTraceabilitysFindCommond?TraceabilityId=" + cookie.get('pTimeId')).then(res => {
        form.entierpriseId = res.data.entierpriseId;
        form.farm = res.data.farm;
        form.principal = res.data.principal;
        form.breedingStock = res.data.breedingStock;
        form.breedingId = res.data.breedingId;
      
    })
}
//上传动检证
const handleAvatarSuccess = () => {
    fileList.value.push(uploadFile)
    FileINfo(fileList.value);
}
//动检证
const FileINfo = (info: any) => {
    let img = "";
    info.map(x => {
        img += x.name + ","

    })
    img = img.substring(0, img.length - 1);
    let Fileurl = reactive({
        img: img,
        pTimeId: cookie.get('pTimeId')
    })
    axios.post("api/Cultivation/GetFileUrl", Fileurl).then(res => {
        if (res.data > 0) {
            ElMessage({
                type: "success",
                message: "完成",
                duration: 2000
            });
            getCultAtionInfo();
            return;
        }
    })
}
//反填动检证
const getFileUrl = () => {
    axios.get("api/Cultivation/GetFileList?pTimeId=" + cookie.get('pTimeId')).then(res => {
        if (res.data == null) return;
        console.log(res.data)
        fileList.value = res.data;
    })
}
//动检证判重
const beforeAvatarUpload: UploadProps['beforeUpload']  = (file: any) => {
    if (fileList.value.findIndex(x => x.name == file.name) != -1) {
        ElMessage({
            type: "warning",
            message: "图片已存在",
            duration: 2000
        });
        return false;
    } else {
        return true;
    }
}
//动检证删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    FileINfo(fileList.value);
}



//添加公司信息(修改)
const submitForm1 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            form1.ptImeId = cookie.get("pTimeId") || "";
            if (form1.id == undefined) {
                axios.post("api/Cultivation/CompanyAdd", form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success("成功");
                        dialogVisible1.value = false;
                    } else {
                        ElMessage.error("失败");
                    }
                })
            } else {
                axios?.put("api/Cultivation/CompanyUpdate", form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success("成功");
                        dialogVisible1.value = false;
                        getCompanyInfo();
                    } else {
                        ElMessage.error("失败");
                    }
                })
            }

        }
    })
}
//反填公司信息
const getCompanyInfo = () => {
    axios.get("api/Cultivation/GetCompanyInfo?pTimeId=" + cookie.get('pTime')).then(res => {
        form1.id = res.data.id;
        form1.companyName = res.data.companyName;
        form1.quantity = res.data.quantity;
        form1.campanyImage = res.data.campanyImage;
        form1.ptImeId = res.data.ptImeId;
        form1.principal = res.data.principal;
        form1.businessCode = res.data.businessCode;
    })
}
//上传公司图片
const handleAvatarSuccess1 = () => {
    fileList1.value.push(uploadFile);
    FileINfo1(fileList1.value);
}
//公司图片
const FileINfo1 = (info: any) => {
    let cImg = "";
    info.map(x => {
        cImg += x.name + ","

    })
    cImg = cImg.substring(0, cImg.length - 1);
    let Fileurl = reactive({
        cImg: cImg,
        pTimeId: cookie.get('pTimeId')
    })
    axios.post("api/Cultivation/GetCompanyFileUrl", Fileurl).then(res => {
        if (res.data > 0) {
            ElMessage({
                type: "success",
                message: "完成",
                duration: 2000
            });

            getCompanyInfo();
            return;
        }
    })
}
//反填公司图片
const getFileUrl1 = () => {
    axios?.get("api/Cultivation/GetCompanyFileList?pTimeId=" + cookie.get('pTimeId')).then(res => {
        if (res.data == null) return;
        console.log(res.data)
        fileList1.value = res.data;
    })
}
//公司图片判重
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (file: any) => {
    if (fileList1.value.findIndex(x => x.name == file.name) != -1) {
        ElMessage({
            type: "warning",
            message: "图片已存在",
            duration: 2000
        });
        return false;
    } else {
        return true;
    }
}
//公司图片删除
const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    FileINfo1(fileList1.value);
}


//免疫列表
const immuneList = ref<{
    id: number,
    pTimeId: any,
    feedingDays: string,
    healthCareMode: string,
    healthCareMethod: string
}[]>([]);
//免疫信息
const immuneInfo = reactive({
    id: 0,
    pTimeId: cookie.get('pTimeId'),
    feedingDays: "",
    healthCareMode: "",
    healthCareMethod: "",
})
//新增行
const NewRow = reactive({
    id: 0,
    pTimeId: cookie.get('pTimeId'),
    feedingDays: "",
    healthCareMode: "",
    healthCareMethod: "",
    isShow: true
})

const immuneIndex = ref(0);


//新增空白行
const addTable = () => {
    if (immuneIndex.value + 2 >= immuneList.value.length) {
        ElMessage({
            type: "warning",
            message: "只能新增二行",
            duration: 2000
        });
        return;
    }


    immuneInfo.id = 0;
    immuneInfo.feedingDays = "";
    immuneInfo.healthCareMethod = "";
    immuneInfo.healthCareMode = "";
    immuneInfo.pTimeId = cookie.get("pTimeId");
    immuneList.value.push(NewRow) || "";

}

//新增行取消
const DelTable = () => {
    immuneList.value.splice(immuneList.value.length - 1, 1);
}


//免疫信息添加(修改)
const Addimmune = () => {

    if (immuneInfo.id == 0) {
        axios.post("api/Immune/ImmuneAdd", immuneInfo).then(res => {
            if (res.data > 0) {
                ElMessage.success("成功");
                NewRow.isShow = false;
                getimmnueList();
            } else {
                ElMessage.error("失败");
            }
        })
    } else {
        axios.put("api/Immune/ImmuneUpdate", immuneInfo).then(res => {
            if (res.data > 0) {
                ElMessage.success("修改成功");
                getimmnueList();
            } else {
                ElMessage.error("修改失败")
            }
        })
    }

}
//免疫信息反填
const getimmuseinfo = (id: number) => {
    axios.get("http://localhost:5020/api/InsertTraceabilityManagements/GetImunitys?BreedingId=" + id).then(res => {
        immuneInfo.id = res.data.id;
        immuneInfo.pTimeId = res.data.pTimeId;
        immuneInfo.feedingDays = res.data.feedingDays;
        immuneInfo.healthCareMode = res.data.healthCareMode;
        immuneInfo.healthCareMethod = res.data.healthCareMethod;
    })
}




//免疫信息列表
const getimmnueList = () => {
    axios.get("api/Immune/GetImmuneList?pTimeId=" + cookie.get('pTimeId')).then(res => {
        immuneList.value = res.data;
        immuneIndex.value = res.data.length;
    })
}

//删除免疫
const deltimmnue = (id: number) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            axios.delete("api/Immune/ImmuneDel?id=" + id).then(res => {
                if (res.data > 0) {
                    ElMessage.success("删除成功");
                    getimmnueList();
                } else {
                    ElMessage.error("删除失败");
                }
            })
        })
}



onMounted(async () => {
    await Promise.all([
getFileUrl(),
    getFileUrl1(),
    getCultAtionInfo(),
    getCompanyInfo(),
    getimmuseinfo(immuneInfo.id),
    getimmnueList(),
    ]) 
})

</script>

<style scoped></style>